package com.biao.mall.cart.controller;

import com.biao.mall.cart.config.ThreadLocalConfig;
import com.biao.mall.cart.service.CartService;
import com.biao.mall.cart.vo.CartItemVo;
import com.biao.mall.cart.vo.CartVo;
import com.biao.mall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
@Slf4j
public class CartController {
    @Autowired
    private CartService cartService;



    @ResponseBody
    @GetMapping("/currentUserCartItems")
    public List<CartItemVo>  getCurrentUserCartItems(){
        return cartService.getUserCartItems();
    }
    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuId") Long skuId,@RequestParam("check") Integer check){
        cartService.checkItem(skuId,check);
        return "redirect:http://cart.mall.com/cart.html";
    }
    @GetMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId") Long skuId){
        cartService.deleteIdCartInfo(skuId.toString());
        return "redirect:http://cart.mall.com/cart.html";
    }

    @GetMapping("/countItem")
    public String countItem(@RequestParam("skuId") Long skuId,@RequestParam("num")Integer num){
        cartService.changeItemCount(skuId,num);
        return "redirect:http://cart.mall.com/cart.html";
    }
    @GetMapping("cart.html")
    public String cartListPage(Model model) {
        CartVo cart = null;
        try {
            cart = cartService.getCart();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        model.addAttribute("cart",cart);
        return "cartList";
    }

    /*
   添加商品到购物车
    */
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num
            , RedirectAttributes ra) throws ExecutionException, InterruptedException {
        cartService.addToCart(skuId, num);
        ra.addAttribute("skuId", skuId);//拼接在路径后
//        ra.addFlashAttribute("skuId", skuId);//存在session中可以再页面取出，只能取一次
        return "redirect:http://cart.mall.com/addToCartSuccess.html";
    }

    @GetMapping("/addToCartSuccess.html")
    public String addToCartSuccessPage(@RequestParam("skuId") Long skuId, Model model) {
        //重定向到成功页面,再次查询购物车数据
        CartItemVo items = cartService.getCartItem(skuId);
        model.addAttribute("items", items);
        return "success";
    }


}
